<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Excel数据对比与冲突合并</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    .conflict-value {
      padding: 0.25rem 0.5rem;
      border-radius: 4px;
      margin-bottom: 0.25rem;
      display: block;
    }
    .conflict-excel {
      background-color: #e0f7fa;
      border-left: 3px solid #3b82f6;
    }
    .conflict-db {
      background-color: #fff8e1;
      border-left: 3px solid #f59e0b;
    }
    .resolved-excel {
      background-color: #e8f5e9;
      border-left: 3px solid #10b981;
    }
    .resolved-db {
      background-color: #f3e5f5;
      border-left: 3px solid #8b5cf6;
    }
    .summary-table-container {
      max-height: 65vh;
      overflow: auto;
      border: 1px solid #e5e7eb;
    }
    .summary-table-container th {
      position: sticky;
      top: 0;
      background: #f9fafb;
    }
    .sticky-column {
      position: sticky;
      left: 0;
      background: white;
      z-index: 5;
    }
    .summary-row.has-conflict {
      background-color: #fef2f2;
    }
    .summary-row.resolved {
      background-color: #f0fdf4;
    }
    .detail-content {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
      gap: 1rem;
      padding: 1rem;
      background-color: #f9fafb;
    }
    .detail-field {
      padding: 0.75rem;
      border-radius: 4px;
      background-color: white;
      border: 1px solid #e5e7eb;
    }
    .radio-option {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      margin-top: 0.5rem;
    }
    .tab-button.active {
      border-bottom: 2px solid #3b82f6;
      color: #3b82f6;
      font-weight: 500;
    }
    .progress-bar {
      height: 0.5rem;
      border-radius: 0.25rem;
    }
  </style>
</head>
<body class="bg-gray-50">
  <div class="container mx-auto py-6 px-4 max-w-7xl">
    <h1 class="text-2xl font-bold mb-6 text-gray-800">Excel数据对比与冲突合并</h1>

    <!-- 上传区域 -->
    <div class="bg-white p-4 rounded-lg shadow-sm mb-6">
      <h2 class="text-lg font-medium mb-3 text-gray-700">上传Excel文件</h2>
      <form id="uploadForm" class="flex flex-col md:flex-row gap-3 items-start">
        <input type="file" name="file" id="fileInput" accept=".xlsx,.xls" 
               class="border border-gray-300 p-2 rounded w-full" required>
        <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 w-full md:w-auto">
          <i class="fas fa-upload mr-2"></i>上传并处理
        </button>
      </form>
      
      <div id="progressContainer" class="hidden mt-4">
        <div class="flex justify-between mb-1 text-sm text-gray-600">
          <span>处理进度</span>
          <span id="progressText">0%</span>
        </div>
        <div class="w-full bg-gray-200 rounded progress-bar">
          <div id="progressBar" class="bg-blue-600 h-full rounded" style="width: 0%"></div>
        </div>
      </div>
      
      <div id="result" class="mt-3 p-2 rounded text-sm hidden"></div>
    </div>

    <!-- 对比结果区域 -->
    <div id="diffResultsContainer" class="hidden bg-white p-4 rounded-lg shadow-sm">
      <h2 class="text-lg font-medium mb-4 text-gray-700">数据对比结果</h2>

      <!-- 标签页导航 -->
      <div class="flex border-b mb-4 overflow-x-auto">
        <button class="tab-button px-4 py-2 text-sm active" data-tab="updated">
          有更新 (<span id="updatedCount">0</span>)
        </button>
        <button class="tab-button px-4 py-2 text-sm" data-tab="new">
          新增 (<span id="newCount">0</span>)
        </button>
        <button class="tab-button px-4 py-2 text-sm" data-tab="deleted">
          数据库独有 (<span id="deletedCount">0</span>)
        </button>
        <button class="tab-button px-4 py-2 text-sm" data-tab="nochange">
          无变化 (<span id="noChangeCount">0</span>)
        </button>
      </div>

      <!-- 标签页内容 -->
      <div id="tabContent">
        <!-- 有更新的记录 -->
        <div id="updated" class="tab-pane">
          <div class="mb-4 text-sm text-gray-600">
            <i class="fas fa-info-circle mr-1 text-blue-500"></i>
            以下记录在Excel和数据库中都存在，但某些字段内容不同。
          </div>
          
          <div class="flex flex-wrap gap-2 mb-4">
            <button id="bulkExcelWins" class="bg-blue-100 text-blue-700 px-3 py-1 rounded text-sm">
              <i class="fas fa-file-excel mr-1"></i>全部采用Excel值
            </button>
            <button id="bulkDBWins" class="bg-yellow-100 text-yellow-700 px-3 py-1 rounded text-sm">
              <i class="fas fa-database mr-1"></i>全部采用数据库值
            </button>
            <button id="markAllResolved" class="bg-green-100 text-green-700 px-3 py-1 rounded text-sm">
              <i class="fas fa-check-circle mr-1"></i>标记所有为已解决
            </button>
          </div>
          
          <div id="updatedRecordsTable" class="summary-table-container">
            <!-- 动态内容将通过JavaScript填充 -->
          </div>
        </div>
        
        <!-- 新增记录 -->
        <div id="new" class="tab-pane hidden">
          <div class="mb-4 text-sm text-gray-600">
            <i class="fas fa-info-circle mr-1 text-green-500"></i>
            以下记录只存在于Excel中，将作为新增记录导入数据库。
          </div>
          
          <div id="newRecordsTable" class="summary-table-container">
            <!-- 动态内容将通过JavaScript填充 -->
          </div>
        </div>
        
        <!-- 数据库独有记录 -->
        <div id="deleted" class="tab-pane hidden">
          <div class="mb-4 text-sm text-gray-600">
            <i class="fas fa-info-circle mr-1 text-red-500"></i>
            以下记录只存在于数据库中，Excel中没有。
          </div>
          
          <div class="flex items-center mb-4">
            <input type="checkbox" id="confirmDeleteMissing" class="mr-2">
            <label for="confirmDeleteMissing" class="text-sm">确认删除数据库中独有的记录</label>
          </div>
          
          <div id="deletedRecordsTable" class="summary-table-container">
            <!-- 动态内容将通过JavaScript填充 -->
          </div>
        </div>
        
        <!-- 无变化记录 -->
        <div id="nochange" class="tab-pane hidden">
          <div class="mb-4 text-sm text-gray-600">
            <i class="fas fa-info-circle mr-1 text-gray-500"></i>
            以下记录在Excel和数据库中完全一致。
          </div>
          
          <div id="noChangeRecordsTable" class="summary-table-container">
            <!-- 动态内容将通过JavaScript填充 -->
          </div>
        </div>
      </div>
      
      <!-- 操作按钮 -->
      <div class="mt-6 pt-4 border-t flex justify-end gap-3">
        <button id="saveChangesBtn" class="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700">
          <i class="fas fa-save mr-1"></i>保存更改
        </button>
        <button id="cancelBtn" class="bg-gray-300 text-gray-800 px-4 py-2 rounded hover:bg-gray-400">
          取消
        </button>
      </div>
    </div>
  </div>

  <script>
    // 全局变量
    let currentDiffResults = null;
    let eventSource = null;
    
    // DOM元素
    const uploadForm = document.getElementById('uploadForm');
    const fileInput = document.getElementById('fileInput');
    const progressContainer = document.getElementById('progressContainer');
    const progressBar = document.getElementById('progressBar');
    const progressText = document.getElementById('progressText');
    const result = document.getElementById('result');
    const diffResultsContainer = document.getElementById('diffResultsContainer');
    
    const updatedRecordsTable = document.getElementById('updatedRecordsTable');
    const newRecordsTable = document.getElementById('newRecordsTable');
    const deletedRecordsTable = document.getElementById('deletedRecordsTable');
    const noChangeRecordsTable = document.getElementById('noChangeRecordsTable');
    
    const updatedCountSpan = document.getElementById('updatedCount');
    const newCountSpan = document.getElementById('newCount');
    const deletedCountSpan = document.getElementById('deletedCount');
    const noChangeCountSpan = document.getElementById('noChangeCount');
    
    const saveChangesBtn = document.getElementById('saveChangesBtn');
    const cancelBtn = document.getElementById('cancelBtn');
    const confirmDeleteMissing = document.getElementById('confirmDeleteMissing');
    
    const bulkExcelWinsBtn = document.getElementById('bulkExcelWins');
    const bulkDBWinsBtn = document.getElementById('bulkDBWins');
    const markAllResolvedBtn = document.getElementById('markAllResolved');

    // 标签页切换
    document.querySelectorAll('.tab-button').forEach(button => {
      button.addEventListener('click', () => {
        // 移除所有active类
        document.querySelectorAll('.tab-button').forEach(btn => {
          btn.classList.remove('active');
        });
        
        // 隐藏所有标签页内容
        document.querySelectorAll('.tab-pane').forEach(pane => {
          pane.classList.add('hidden');
        });
        
        // 激活当前标签
        button.classList.add('active');
        document.getElementById(button.dataset.tab).classList.remove('hidden');
      });
    });
    
    // 上传表单处理
    uploadForm.addEventListener('submit', function(e) {
      e.preventDefault();
      const file = fileInput.files[0];
      if (!file) {
        showMessage('error', '请选择要上传的Excel文件');
        return;
      }
      
      // 重置UI状态
      resetUI();
      showMessage('info', '文件上传中...');
      
      const formData = new FormData();
      formData.append('file', file);
      
      fetch('/api/upload', {
        method: 'POST',
        body: formData
      })
      .then(response => {
        if (!response.ok) {
          return response.json().then(err => { throw new Error(err.message || '上传失败'); });
        }
        return response.json();
      })
      .then(data => {
        showMessage('success', data.message || '文件上传成功，正在处理...');
        progressContainer.classList.remove('hidden');
        startSSE();
      })
      .catch(error => {
        showMessage('error', '上传失败: ' + error.message);
        progressContainer.classList.add('hidden');
      });
    });
    
    // 启动SSE连接
    function startSSE() {
      if (eventSource) {
        eventSource.close();
      }
      
      eventSource = new EventSource('/api/events');
      
      eventSource.onmessage = function(event) {
        try {
          const data = JSON.parse(event.data);
          
          if (data.type === 'error') {
            updateProgress(0, '❌ ' + data.message, true, 'error');
            showMessage('error', '处理失败: ' + data.message);
            eventSource.close();
            return;
          }
          
          if (data.message) {
            progressText.textContent = data.message;
          }
          
          if (typeof data.progress === 'number') {
            updateProgress(data.progress, data.message);
          }
          
          if (data.done && data.data) {
            updateProgress(100, data.message || '处理完成', true, 'success');
            showMessage('success', data.message || '文件处理完成');
            eventSource.close();
            
            // 存储并渲染对比结果
            currentDiffResults = data.data;
            renderDiffResults(data.data);
          }
        } catch (e) {
          console.error('解析SSE消息错误:', e);
          updateProgress(0, '解析进度消息错误', true, 'error');
          showMessage('error', '处理过程中发生错误');
        }
      };
      
      eventSource.onerror = function() {
        progressText.textContent = '连接中断';
        showMessage('error', '与服务器的连接中断');
        eventSource.close();
      };
    }
    
    // 更新进度条
    function updateProgress(progress, message, done = false, type = 'info') {
      progressBar.style.width = `${progress}%`;
      progressText.textContent = `${Math.round(progress)}% ${message || ''}`;
      
      if (done) {
        progressContainer.classList.add('hidden');
        diffResultsContainer.classList.remove('hidden');
      }
    }
    
    // 显示消息
    function showMessage(type, message) {
      result.textContent = message;
      result.className = 'mt-3 p-2 rounded text-sm';
      
      if (type === 'success') {
        result.classList.add('bg-green-100', 'text-green-700');
      } else if (type === 'error') {
        result.classList.add('bg-red-100', 'text-red-700');
      } else if (type === 'info') {
        result.classList.add('bg-blue-100', 'text-blue-700');
      }
      
      result.classList.remove('hidden');
    }
    
    // 重置UI状态
    function resetUI() {
      result.textContent = '';
      result.className = 'mt-3 p-2 rounded text-sm hidden';
      progressContainer.classList.add('hidden');
      progressBar.style.width = '0%';
      progressText.textContent = '0%';
      diffResultsContainer.classList.add('hidden');
      currentDiffResults = null;
      confirmDeleteMissing.checked = false;
    }
    
    // 渲染对比结果
    function renderDiffResults(diffs) {
      // 更新计数
      updatedCountSpan.textContent = diffs.updatedRecords.length;
      newCountSpan.textContent = diffs.newRecords.length;
      deletedCountSpan.textContent = diffs.deletedOrMissingInExcel.length;
      noChangeCountSpan.textContent = diffs.noChangeRecords.length;
      
      // 初始化解决状态
      diffs.updatedRecords.forEach(record => {
        if (!record.resolved) {
          record.resolved = {};
        }
        
        // 为每个冲突字段设置默认解决方案
        for (const field in record.changes) {
          if (!(field in record.resolved)) {
            record.resolved[field] = 'db'; // 默认使用数据库值
          }
        }
        
        // 标记是否展开
        record.isExpanded = false;
      });
      
      // 渲染各类型记录
      renderUpdatedRecords(diffs.updatedRecords);
      renderNewRecords(diffs.newRecords);
      renderDeletedRecords(diffs.deletedOrMissingInExcel);
      renderNoChangeRecords(diffs.noChangeRecords);
      
      // 默认显示有更新的记录标签页
      document.querySelector('.tab-button[data-tab="updated"]').click();
    }
    
    // 渲染有更新的记录
    function renderUpdatedRecords(records) {
      if (records.length === 0) {
        updatedRecordsTable.innerHTML = '<p class="text-center py-4 text-gray-500">没有需要更新的记录</p>';
        return;
      }
      
      const table = document.createElement('table');
      table.className = 'min-w-full';
      
      let html = `
        <thead>
          <tr class="text-left text-sm text-gray-600 bg-gray-50">
            <th class="p-2 sticky-column">订单号</th>
            <th class="p-2">项目编码</th>
            <th class="p-2">铁塔站址名称</th>
            <th class="p-2">冲突字段</th>
            <th class="p-2">操作</th>
          </tr>
        </thead>
        <tbody class="text-sm">
      `;
      
      records.forEach(record => {
        const conflictsCount = Object.keys(record.changes).length;
        const resolvedCount = Object.values(record.resolved).filter(v => v).length;
        const isResolved = conflictsCount === resolvedCount;
        
        // 获取第一个冲突字段的值对比
        const firstConflictField = Object.keys(record.changes)[0];
        const firstConflict = record.changes[firstConflictField];
        
        html += `
          <tr class="summary-row ${isResolved ? 'resolved' : 'has-conflict'} border-b" data-order-num="${record.orderNum}">
            <td class="p-2 sticky-column">${record.orderNum}</td>
            <td class="p-2">
              ${firstConflict ? `<span class="text-blue-600">${firstConflict.excel}</span> → <span class="text-yellow-600">${firstConflict.db}</span>` : '-'}
            </td>
            <td class="p-2">${record.excelRecord['铁塔站址名称'] || '-'}</td>
            <td class="p-2">
              ${Object.keys(record.changes).map(field => 
                `<span class="bg-red-100 text-red-800 px-2 py-0.5 rounded-full text-xs">${field}</span>`
              ).join(' ')}
            </td>
            <td class="p-2">
              <button class="text-blue-600 text-sm" data-action="toggle-detail" data-order-num="${record.orderNum}">
                <i class="fas fa-${record.isExpanded ? 'chevron-up' : 'chevron-down'} mr-1"></i>${record.isExpanded ? '收起' : '展开'}
              </button>
            </td>
          </tr>
          <tr class="detail-row ${record.isExpanded ? '' : 'hidden'}" id="detail-row-${record.orderNum}">
            <td colspan="5" class="p-0">
              <div class="detail-content">
                <div class="col-span-full mb-2">
                  <h3 class="font-medium">记录详情: ${record.orderNum}</h3>
                </div>
        `;
        
        // 渲染所有字段
        ['项目编码', '铁塔站址名称', '铁塔站址编码', '需求提出时间', '实际订单确认时间', '立项时间'].forEach(field => {
          const isConflict = record.changes[field];
          const resolvedSource = record.resolved[field];
          
          html += `
            <div class="detail-field ${isConflict ? 'bg-red-50' : ''}">
              <label class="font-medium">${field}</label>
          `;
          
          if (isConflict) {
            html += `
              <div class="conflict-value conflict-excel ${resolvedSource === 'excel' ? 'resolved-excel' : ''}">
                Excel: ${record.changes[field].excel}
              </div>
              <div class="conflict-value conflict-db ${resolvedSource === 'db' ? 'resolved-db' : ''}">
                数据库: ${record.changes[field].db}
              </div>
              <div class="radio-option">
                <input type="radio" name="resolve-${record.orderNum}-${field}" value="excel" 
                       data-order-num="${record.orderNum}" data-field="${field}"
                       ${resolvedSource === 'excel' ? 'checked' : ''}>
                <span>使用Excel值</span>
              </div>
              <div class="radio-option">
                <input type="radio" name="resolve-${record.orderNum}-${field}" value="db" 
                       data-order-num="${record.orderNum}" data-field="${field}"
                       ${resolvedSource === 'db' ? 'checked' : ''}>
                <span>使用数据库值</span>
              </div>
            `;
          } else {
            // 无冲突字段
            const value = record.excelRecord[field] || record.dbRecord[field] || '-';
            html += `<div>${value}</div>`;
          }
          
          html += `</div>`; // 结束detail-field
        });
        
        // 添加记录级操作按钮
        html += `
                <div class="col-span-full flex justify-end gap-2 mt-2">
                  <button class="record-excel-wins bg-blue-100 text-blue-700 px-3 py-1 rounded text-sm" 
                          data-order-num="${record.orderNum}">
                    <i class="fas fa-file-excel mr-1"></i>整条记录采用Excel版本
                  </button>
                  <button class="record-db-wins bg-yellow-100 text-yellow-700 px-3 py-1 rounded text-sm" 
                          data-order-num="${record.orderNum}">
                    <i class="fas fa-database mr-1"></i>整条记录采用数据库版本
                  </button>
                </div>
              </div>
            </td>
          </tr>
        `;
      });
      
      html += `</tbody>`;
      table.innerHTML = html;
      updatedRecordsTable.innerHTML = '';
      updatedRecordsTable.appendChild(table);
      
      // 添加事件监听器
      addEventListeners();
    }
    
    // 渲染新增记录
    function renderNewRecords(records) {
      if (records.length === 0) {
        newRecordsTable.innerHTML = '<p class="text-center py-4 text-gray-500">没有新增记录</p>';
        return;
      }
      
      const table = document.createElement('table');
      table.className = 'min-w-full';
      
      let html = `
        <thead>
          <tr class="text-left text-sm text-gray-600 bg-gray-50">
            <th class="p-2 sticky-column">订单号</th>
            <th class="p-2">项目编码</th>
            <th class="p-2">铁塔站址名称</th>
            <th class="p-2">需求提出时间</th>
          </tr>
        </thead>
        <tbody class="text-sm">
      `;
      
      records.forEach(record => {
        html += `
          <tr class="border-b">
            <td class="p-2 sticky-column">${record[ID_FIELD]}</td>
            <td class="p-2">${record['项目编码'] || '-'}</td>
            <td class="p-2">${record['铁塔站址名称'] || '-'}</td>
            <td class="p-2">${record['需求提出时间'] || '-'}</td>
          </tr>
        `;
      });
      
      html += `</tbody>`;
      table.innerHTML = html;
      newRecordsTable.innerHTML = '';
      newRecordsTable.appendChild(table);
    }
    
    // 渲染数据库独有记录
    function renderDeletedRecords(records) {
      if (records.length === 0) {
        deletedRecordsTable.innerHTML = '<p class="text-center py-4 text-gray-500">没有数据库独有的记录</p>';
        return;
      }
      
      const table = document.createElement('table');
      table.className = 'min-w-full';
      
      let html = `
        <thead>
          <tr class="text-left text-sm text-gray-600 bg-gray-50">
            <th class="p-2 sticky-column">订单号</th>
            <th class="p-2">项目编码</th>
            <th class="p-2">铁塔站址名称</th>
          </tr>
        </thead>
        <tbody class="text-sm">
      `;
      
      records.forEach(record => {
        html += `
          <tr class="border-b">
            <td class="p-2 sticky-column">${record[ID_FIELD]}</td>
            <td class="p-2">${record['项目编码'] || '-'}</td>
            <td class="p-2">${record['铁塔站址名称'] || '-'}</td>
          </tr>
        `;
      });
      
      html += `</tbody>`;
      table.innerHTML = html;
      deletedRecordsTable.innerHTML = '';
      deletedRecordsTable.appendChild(table);
    }
    
    // 渲染无变化记录
    function renderNoChangeRecords(records) {
      if (records.length === 0) {
        noChangeRecordsTable.innerHTML = '<p class="text-center py-4 text-gray-500">没有无变化的记录</p>';
        return;
      }
      
      const table = document.createElement('table');
      table.className = 'min-w-full';
      
      let html = `
        <thead>
          <tr class="text-left text-sm text-gray-600 bg-gray-50">
            <th class="p-2 sticky-column">订单号</th>
            <th class="p-2">项目编码</th>
            <th class="p-2">铁塔站址名称</th>
            <th class="p-2">需求提出时间</th>
          </tr>
        </thead>
        <tbody class="text-sm">
      `;
      
      records.forEach(record => {
        html += `
          <tr class="border-b">
            <td class="p-2 sticky-column">${record[ID_FIELD]}</td>
            <td class="p-2">${record['项目编码'] || '-'}</td>
            <td class="p-2">${record['铁塔站址名称'] || '-'}</td>
            <td class="p-2">${record['需求提出时间'] || '-'}</td>
          </tr>
        `;
      });
      
      html += `</tbody>`;
      table.innerHTML = html;
      noChangeRecordsTable.innerHTML = '';
      noChangeRecordsTable.appendChild(table);
    }
    
    // 添加事件监听器
    function addEventListeners() {
      // 展开/收起详情
      document.querySelectorAll('[data-action="toggle-detail"]').forEach(button => {
        button.addEventListener('click', (e) => {
          const orderNum = e.target.dataset.orderNum;
          const record = currentDiffResults.updatedRecords.find(r => r.orderNum === orderNum);
          if (!record) return;
          
          record.isExpanded = !record.isExpanded;
          const detailRow = document.getElementById(`detail-row-${orderNum}`);
          if (detailRow) {
            detailRow.classList.toggle('hidden');
            e.target.innerHTML = record.isExpanded ? 
              '<i class="fas fa-chevron-up mr-1"></i>收起' : 
              '<i class="fas fa-chevron-down mr-1"></i>展开';
          }
        });
      });
      
      // 字段级单选按钮
      document.querySelectorAll('input[type="radio"][name^="resolve-"]').forEach(radio => {
        radio.addEventListener('change', (e) => {
          const orderNum = e.target.dataset.orderNum;
          const field = e.target.dataset.field;
          const source = e.target.value;
          
          const record = currentDiffResults.updatedRecords.find(r => r.orderNum === orderNum);
          if (record) {
            record.resolved[field] = source;
            
            // 更新UI样式
            const fieldDiv = e.target.closest('.detail-field');
            if (fieldDiv) {
              fieldDiv.querySelectorAll('.conflict-value').forEach(el => {
                el.classList.remove('resolved-excel', 'resolved-db');
              });
              
              if (source === 'excel') {
                fieldDiv.querySelector('.conflict-excel').classList.add('resolved-excel');
              } else {
                fieldDiv.querySelector('.conflict-db').classList.add('resolved-db');
              }
            }
            
            // 更新行状态
            updateRowStatus(orderNum);
          }
        });
      });
      
      // 记录级操作 - 采用Excel版本
      document.querySelectorAll('.record-excel-wins').forEach(button => {
        button.addEventListener('click', (e) => {
          const orderNum = e.target.dataset.orderNum;
          const record = currentDiffResults.updatedRecords.find(r => r.orderNum === orderNum);
          if (!record) return;
          
          // 将所有冲突字段设置为使用Excel值
          for (const field in record.changes) {
            record.resolved[field] = 'excel';
            
            // 更新UI
            const radio = document.querySelector(`input[name="resolve-${orderNum}-${field}"][value="excel"]`);
            if (radio) {
              radio.checked = true;
              
              const fieldDiv = radio.closest('.detail-field');
              if (fieldDiv) {
                fieldDiv.querySelectorAll('.conflict-value').forEach(el => {
                  el.classList.remove('resolved-excel', 'resolved-db');
                });
                fieldDiv.querySelector('.conflict-excel').classList.add('resolved-excel');
              }
            }
          }
          
          updateRowStatus(orderNum);
        });
      });
      
      // 记录级操作 - 采用数据库版本
      document.querySelectorAll('.record-db-wins').forEach(button => {
        button.addEventListener('click', (e) => {
          const orderNum = e.target.dataset.orderNum;
          const record = currentDiffResults.updatedRecords.find(r => r.orderNum === orderNum);
          if (!record) return;
          
          // 将所有冲突字段设置为使用数据库值
          for (const field in record.changes) {
            record.resolved[field] = 'db';
            
            // 更新UI
            const radio = document.querySelector(`input[name="resolve-${orderNum}-${field}"][value="db"]`);
            if (radio) {
              radio.checked = true;
              
              const fieldDiv = radio.closest('.detail-field');
              if (fieldDiv) {
                fieldDiv.querySelectorAll('.conflict-value').forEach(el => {
                  el.classList.remove('resolved-excel', 'resolved-db');
                });
                fieldDiv.querySelector('.conflict-db').classList.add('resolved-db');
              }
            }
          }
          
          updateRowStatus(orderNum);
        });
      });
      
      // 批量操作 - 全部采用Excel值
      bulkExcelWinsBtn.addEventListener('click', () => {
        if (!currentDiffResults || !currentDiffResults.updatedRecords) return;
        
        currentDiffResults.updatedRecords.forEach(record => {
          for (const field in record.changes) {
            record.resolved[field] = 'excel';
          }
        });
        
        // 重新渲染以更新UI
        renderUpdatedRecords(currentDiffResults.updatedRecords);
      });
      
      // 批量操作 - 全部采用数据库值
      bulkDBWinsBtn.addEventListener('click', () => {
        if (!currentDiffResults || !currentDiffResults.updatedRecords) return;
        
        currentDiffResults.updatedRecords.forEach(record => {
          for (const field in record.changes) {
            record.resolved[field] = 'db';
          }
        });
        
        // 重新渲染以更新UI
        renderUpdatedRecords(currentDiffResults.updatedRecords);
      });
      
      // 批量操作 - 标记所有为已解决
      markAllResolvedBtn.addEventListener('click', () => {
        if (!currentDiffResults || !currentDiffResults.updatedRecords) return;
        
        currentDiffResults.updatedRecords.forEach(record => {
          for (const field in record.changes) {
            // 默认使用数据库值作为解决方案
            record.resolved[field] = 'db';
          }
        });
        
        // 重新渲染以更新UI
        renderUpdatedRecords(currentDiffResults.updatedRecords);
      });
      
      // 保存更改
      saveChangesBtn.addEventListener('click', async () => {
        if (!currentDiffResults) {
          showMessage('error', '没有可保存的更改');
          return;
        }
        
        try {
          saveChangesBtn.disabled = true;
          showMessage('info', '正在保存更改到数据库...');
          
          // 准备要保存的数据
          const newRecords = currentDiffResults.newRecords;
          const updatedRecords = [];
          const deletedRecords = [];
          
          // 处理更新的记录
          currentDiffResults.updatedRecords.forEach(record => {
            const finalRecord = { ...record.dbRecord };
            
            // 应用用户选择的解决方案
            for (const field in record.changes) {
              finalRecord[field] = record.resolved[field] === 'excel' 
                ? record.excelRecord[field] 
                : record.dbRecord[field];
            }
            
            updatedRecords.push(finalRecord);
          });
          
          // 处理删除的记录
          if (confirmDeleteMissing.checked) {
            currentDiffResults.deletedOrMissingInExcel.forEach(record => {
              deletedRecords.push(record[ID_FIELD]);
            });
          }
          
          // 发送到后端
          const response = await fetch('/api/apply-changes', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              newRecords,
              updatedRecords,
              deletedRecords
            })
          });
          
          if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.message || '保存失败');
          }
          
          const data = await response.json();
          showMessage('success', data.message || '所有更改已成功保存');
          diffResultsContainer.classList.add('hidden');
        } catch (error) {
          console.error('保存更改失败:', error);
          showMessage('error', '保存更改失败: ' + error.message);
        } finally {
          saveChangesBtn.disabled = false;
        }
      });
      
      // 取消按钮
      cancelBtn.addEventListener('click', () => {
        if (confirm('确定要取消所有未保存的更改吗？')) {
          resetUI();
          showMessage('info', '操作已取消');
        }
      });
    }
    
    // 更新行状态
    function updateRowStatus(orderNum) {
      const record = currentDiffResults.updatedRecords.find(r => r.orderNum === orderNum);
      if (!record) return;
      
      const conflictsCount = Object.keys(record.changes).length;
      const resolvedCount = Object.values(record.resolved).filter(v => v).length;
      const isResolved = conflictsCount === resolvedCount;
      
      const row = document.querySelector(`.summary-row[data-order-num="${orderNum}"]`);
      if (row) {
        row.classList.toggle('has-conflict', !isResolved);
        row.classList.toggle('resolved', isResolved);
      }
    }
    
    // 初始化
    document.addEventListener('DOMContentLoaded', () => {
      // 默认激活第一个标签页
      document.querySelector('.tab-button[data-tab="updated"]').click();
    });
  </script>
</body>
</html>